package com.DCapps.sendakiss;

import static com.DCapps.sendakiss.CommonUtilities.SERVER_URL_GETFRIENDS;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import adapters.ListAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.DCapps.sendakiss.helper.Helper;
import com.DCapps.sendakiss.helper.JSONParser;
import com.DCapps.sendakiss.helper.SQLHelper;

public class UserListActivity extends Activity implements OnItemSelectedListener {

	public static final String TAG_NAME = "name";
	public static final String TAG_SUCCESS = "success";
	public static final String TAG_Result = "result";
	public static final String TAG_GCMID = "gcmid";
	public static final String TAG_email = "email";
	
	ListAdapter la;

	ArrayList<Friend> myFriends;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			setContentView(R.layout.friend_list);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		SQLHelper sqlh = new SQLHelper(this);

		myFriends = sqlh.getFriends();

		ListView lv = (ListView) findViewById(R.id.jazzlistview);
		lv.setOnItemSelectedListener(this);
		la = new ListAdapter(getApplicationContext(), R.layout.item, myFriends);
		
		lv.setAdapter(la);
		la.notifyDataSetChanged();

	}

	class LoadAllProducts extends AsyncTask<String, String, ArrayList<Friend>> {

		private ProgressDialog pDialog = null;
		private JSONParser jParser = new JSONParser();

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(UserListActivity.this);
			pDialog.setMessage("Loading friends. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected ArrayList<Friend> doInBackground(String... args) {

			ArrayList<Friend> friends = new ArrayList<Friend>();
			JSONArray JSONnbrs = null;

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			

			for (String s : Helper.getAllPhoneNumbers(UserListActivity.this)) {
				if (s != null && s.compareTo("0") != 0) {
					params.add(new BasicNameValuePair("nbr[]", s));
				}

			}

			params.clear();
			params.add(new BasicNameValuePair("nbr[]", "3252277219"));
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(SERVER_URL_GETFRIENDS,
					"GET", params);

			// Check your log cat for JSON reponse
			Log.d("All Products: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				
				int success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					// products found
					// Getting Array of Products
					JSONnbrs = json.getJSONArray(TAG_Result);

					// looping through All Products
					for (int i = 0; i < JSONnbrs.length(); i++) {
						JSONObject c = JSONnbrs.getJSONObject(i);

						Friend f = new Friend();
						f.setPhoneNumber(c.getString(TAG_email));
						f.setGCMID(c.getString(TAG_GCMID));
						
						
						
						friends.add(f);
					}
				} else {
					// no products found
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return Helper.getFriends(friends, UserListActivity.this);
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(final ArrayList<Friend> friends) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					myFriends.clear();
					myFriends = friends;
					la.notifyDataSetChanged();
				}
			});

		}

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		
		switch (item.getItemId()) {
		case R.id.reloadFrends:
			new LoadAllProducts().execute("");
			break;

		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	

}
